import axios from 'axios';
import { useMessage } from '@/hooks/useMessage';
import store from '@/store';

const ElMessage=useMessage();
const service=axios.create({
    //项目所处的环境
    baseURL:process.env.VUE_APP_URL,
    timeout:1000*60*5
});

//请求拦截器  ElMessage
service.interceptors.request.use(
    (config)=>{
        const tokenStr=store.state.userStore.token;
        //请求携带token字段
        if(tokenStr && (!config.url.includes('/api/api/userlogin'))){
            //在请求头部添加token认证字段
            config.headers[process.env.VUE_APP_AJAX_HEADER_AUTH_NAME]=tokenStr;
        }
        return config;
    },
    (err)=>{
        Promise.reject(err)
    }
);

//响应拦截器
service.interceptors.response.use(
    (response)=>{
        if(response.data.code!==200){
            ElMessage({
                showClose:true,
                message:response.data.message,//错误消息提示
                type:"error"
            });
            return Promise.reject(response.data.message);
        }else{
            console.log(response.data);
            return response.data;
        } 
    },
    (err)=>{
        Promise.reject(err);
    }
);
export default service;